# -*- coding: utf-8 -*- 
'''
Created on 2 sept. 2012

@author: Olivier
'''
import threading
from Data.Player import Player, NewPlayer, PlayerList, ClickPlayer, MovePlayer,\
    UpdatePlayer
from Data.TchatPlayer import TchatPlayer

class ServerClientDataTreatment(threading.Thread):
    '''
    classdocs
    '''


    def __init__(self, inServerClientTreatment, inData):
        '''
        Constructor
        '''
        threading.Thread.__init__(self)
        
        self.__mServerClientTreatment = inServerClientTreatment
        self.__mData = inData
        
        self.start()
        
    def run(self):
        '''
        Function to treat the data
        '''
        if self.__mData == 'Disconnect': #if disconnect : stop client
            print 'Client Disconnect'
            self.__mServerClientTreatment.Send('DisconnectOk')
            self.__mServerClientTreatment.Stop()
        
        elif type(self.__mData) == Player: #check if we can send an object and print object
            print "PLAYER", self.__mData
        elif type(self.__mData) == TchatPlayer:
            self.__mServerClientTreatment.GetServer().SendToAll(self.__mData)
        elif type(self.__mData) == NewPlayer:
            self.__mServerClientTreatment.GetServer().GetPlayerList().append(self.__mData.GetPlayer())
            thePLayerList = PlayerList(self.__mServerClientTreatment.GetServer().GetPlayerList())
            self.__mServerClientTreatment.GetServer().SendToAll(thePLayerList)
        elif type(self.__mData) == ClickPlayer:
            self.__mServerClientTreatment.GetServer().SendToAll(self.__mData)
            self.__mServerClientTreatment.GetServer().SetClickPoint(self.__mData.GetPosition())
            if self.__DetectionColision():
                thePlayer = self.__mData.GetPlayer()
                thePlayer.SetScore(thePlayer.GetScore()+1)
                self.__mServerClientTreatment.GetServer().SendToAll(UpdatePlayer(thePlayer))
        elif type(self.__mData) == MovePlayer:
            self.__mServerClientTreatment.GetServer().SendToAll(self.__mData)
            self.__mServerClientTreatment.GetServer().SetBitePoint(self.__mData.GetPositionBite())
        else:  #print string
            print "MSG", self.__mData
            
    def __DetectionColision(self):
        theClickX, theClickY = self.__mServerClientTreatment.GetServer().GetClickPoint()
        theMoveX, theMoveY = self.__mServerClientTreatment.GetServer().GetBitePoint()
        theZoneSize = 5
        return (theClickX > theMoveX - theZoneSize) and (theClickX < theMoveX + theZoneSize) and \
            (theClickY > theMoveY - theZoneSize) and (theClickY < theMoveY + theZoneSize) 

            